<template>
  <div class="deduction">
    <template v-if="remainingTime >= 0">
      倒计时:
      <template v-if="day">
        <span class="day">{{ day }}</span
        >天
      </template>
      <span class="num">{{ hour }}</span
      >:<span class="num">{{ minute }}</span
      >:<span class="num">{{ second }}</span>
    </template>
  </div>
</template>
<script>
export default {
  props: {
    // 接收父组件传入的时间
    time: {
      type: Number,
      required: true,
      default: 0
    }
  },
  data() {
    return {
      timer: null,
      remainingTime: 0,
      day: '',
      hour: '',
      minute: '',
      second: '',
      surplu: ''
    }
  },
  methods: {
    countDown() {
      let time = this.remainingTime
      if (time >= 0) {
        let days = Math.floor(time / (60 * 60 * 24)) //计算天数
        let hours = Math.floor((time / (60 * 60)) % 24) //计算小时数
        let minutes = Math.floor((time / 60) % 60) //计算分钟数
        let seconds = Math.floor(time % 60) //计算秒数
        --this.remainingTime
        //添加定时器，显示这个时间
        this.day = days
        this.hour = this.format(hours)
        this.minute = this.format(minutes)
        this.second = this.format(seconds)
      } else {
        this.day = ''
        this.hour = ''
        this.minute = ''
        this.second = ''
      }
    },

    //修正  把 8秒 变成08 秒
    format(x) {
      return x >= 10 ? x : `0${x}`
    }
  },
  mounted() {
    this.remainingTime = this.time
    //先执行一次 防止刚打开页面要等1秒才出现倒计时
    this.countDown()
    this.timer = setInterval(this.countDown, 1000)
  },
  //切换组件关闭定时器
  destoryed() {
    clearInterval(this.timer)
  }
}
</script>
<style lang="scss" scoped>
.deduction {
  display: flex;
  align-items: center;
  font-size: 12px;
  font-weight: 400;
  color: $text-color-import;
  line-height: 1;
  .day {
    color: #f54030;
    margin: 0 4px;
  }
  .num {
    margin: 0 4px;
    padding: 0 2px;
    font-size: 12px;
    font-weight: 400;
    color: #ffffff;
    line-height: 16px;
    background: #f54030;
    border-radius: 4px;
  }
}
</style>
